const Router = require('@koa/router')
const mongoose = require('mongoose')
const Order = mongoose.model('Order')

const router = new Router({
    prefix: '/order',
})
/**新增 */
router.post('/updateandadd', async (ctx) => {
    let {
        _id,
        cusId,
        cusName,
        cusPhone,
        projectId,
        projectName,
        orderDate,
        payState,
    } = ctx.request.body
    const one = await Order.findOne({
        _id,
    })
    if (one) {
        //更新
        one.cusId = cusId
        one.cusName = cusName
        one.cusPhone = cusPhone
        one.projectId = projectId
        one.projectName = projectName
        one.orderDate = orderDate
        one.payState = payState
        const res = await one.save()
        ctx.body = {
            data: res,
            msg: '更新成功',
            code: 200
        }
    } else {
        //新增
        if (cusId == "" || projectId == "") {
            ctx.body = {
                data: null,
                code: 0,
                msg: '客户id,项目id必有',
            }
            return
        }
        const order = new Order({
            cusId,
            cusName,
            cusPhone,
            projectId,
            projectName,
            orderDate,
            payState,
        })
        const res = await order.save()
        ctx.body = {
            data: res,
            code: 200,
            msg: '新增项目成功'
        }
    }
})
/**列表 */
router.get('/list', async (ctx) => {
    let {
        page,
        size,
        keyword
    } = ctx.query
    page = Number(page)
    size = Number(size)

    let reg = new RegExp(keyword, "gim")

    const list = await Order
        .find({ "cusName": { $regex: reg } })
        .sort({ _id: -1 }) //-1倒序
        .skip((page - 1) * size)
        .limit(size).exec()

    const total = await Order.countDocuments().exec()
    ctx.body = {
        msg: '获取列表成功',
        data: {
            list,
            page,
            size,
            total
        },
        code: 200
    }
})
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const res = await Order.deleteOne({
        _id: id
    })
    ctx.body = {
        code: 200,
        msg: '删除成功',
        data: res
    }
})
module.exports = router